import { config } from '../config.js'
const tips = {
  1: '抱歉出现一个错误',
  404: '找不到内容'
}
class HTTP {
  tokenKey = 'token';
  request({method='GET',url,data={},myHeader={}}){
    return new Promise((resolve,reject)=>{
      wx.request({
        url: config.base_url+url,
        data:Object.assign(
          {
            'appkey': 'aQqRB9kpEYB3CSXd'
          },data
        ),
        method,
        header: Object.assign({
          'Content-Type': 'application/json',
        },myHeader),
        success:(res)=>{
          let code = res.statusCode.toString()
          if (code.startsWith('2')) {
            resolve(res);
          } else if (code.includes('403')){
            //token过期
            reject(res);
          }
          else{
           this._show_error(code) 
          }
        },
        fail:(error)=>{
         this._show_error(1);
      
        },
      })
    });
  }
  _show_error(code){
    if(!code){
      code=1;
    }
    const tip = tips[code]
    wx.showToast({
      title: tip?tip:"未知错误",
      icon:'none',
      duration:2000
    })
  }
  getToken() {
    const token = wx.getStorageSync(this.tokenKey) || '';
    return token;
  }
  setToken(token) {
    wx.setStorageSync(this.tokenKey, token);
  }
  validateToken() {
    return this.request({
      method: "post",
      url: 'jwt-auth/v1/token/validate',
      myHeader: {
        'Authorization': `Bearer ${this.getToken()}`
      }
    });
  }
}
export { HTTP }